﻿var advanceClick = false;
var objTable;
var hidden = '';
var isSelectAll = false;
var totalRecords = 0;
var departmentId = 0;
var locationId = 0;

function getLocationId() {
    $.ajax({
        url: '/AccountCourse/GetLocation',
        type: 'POST',
        dataType: 'json',
        data: {},
        success: function (result) {
            $('#accountLocation').html('');
            for (var i = 0; i < result.length; i++) {
                $('#accountLocation').append('<option id="' + result[i].LocationId + '">' + result[i].LocationName + '</option>');
            }

            $('#accountLocation option').each(function () {
                $(this).click(function () {
                    locationId = $(this).attr('id');
                });
            });
        },
        error: function () {
            alert('error getlocation');
        }
    });
}
//Create Tree Menu 
function CreateTreeMenuById(id) {
    $('#' + id).treeview({
        collapsed: true,
        animated: "fast",
        prerendered: true,
        persist: "location"
    });

    $("#" + id + " li ul li a").click(function () {
        $("#" + id + " li span").removeClass("selected");
        $("#" + id + " li ul li a").removeClass("selected");
        $("#" + id + " li a").removeClass("selected");
        $('#all').removeClass('selected');
        $(this).addClass("selected");
    });

    $("#" + id + " li ul li a").click(function () {
        $("#" + id + " li span").removeClass("selected");
        $("#" + id + " li ul li a").removeClass("selected");
        $("#" + id + " li a").removeClass("selected");
        $('#all').removeClass('selected');
        $(this).addClass("selected");
    });

    $("#" + id + " span").click(function () {
        $("#tree span").removeClass("selected");
        $("#tree li ul li a").removeClass("selected");
        $("#" + id + " li a").removeClass("selected");
        $('#all').removeClass('selected');
        $(this).addClass("selected");
    });

    $("#" + id + " li a").click(function () {
        $("#" + id + " li a").removeClass("selected");
        $("#tree span").removeClass("selected");
        $("#tree li ul li a").removeClass("selected");
        $('#all').removeClass('selected');
        $(this).addClass("selected");
    });
}

function PrepareTree() {

    $('#treeWrapper').prepend('<span class="selected" id="all" style="cursor:pointer">All</span>');
    $('#all').click(function () {
        departmentId = 0;
        getDataFromDatabase('dataTables', 1, $('#dataTables_length option:selected').text());
    });
    $('#all').click(function () {
        $(this).addClass('selected');
        $('li a').removeClass('selected');
        $('li span').removeClass('selected');
    });
    var uls = $('#treeWrapper li:has(ul)');
    uls.each(function () {
        $(this).prepend('<div class="hitarea expandable-hitarea"></div>');
    });
    var a = $('#treeWrapper li:has(ul) a');
    a.each(function () {
        $(this).replaceWith('<span onclick="getTreeViewDataClick(this)">' + $(this).html() + '</span>');
    });
    var obj = $('#treeWrapper ul:first');
    obj.attr('id', 'tree');
    obj.removeClass('hidden');
    obj.addClass('treeview');
    setIdDepartment($('#treeWrapper li a'));
    setIdDepartment($('#treeWrapper li span'));
}

//Get departmentId
function getTreeViewDataClick(sender) {
    departmentId = sender.id;
}

function setIdDepartment(obj) {
    obj.each(function () {
        var val = $(this).text();
        var n = val.length;
        while (n > 0) {
            if (val[n] == '_') {
                break;
            }
            n--;
        }
        $(this).attr('id', val.substring(n + 1, val.length));
        $(this).text(val.substring(0, n));
        $(this).click(function () {
            getDataFromDatabase('dataTables', 1, $('#dataTables_length option:selected').text());
        });
    });
}

//

function formatDate() {
    $('.dDate').each(function () {
        //todo
    });
}
//Initial in Account-Course index
function Initial() {
    $('#selectAll').click(function () {
        isSelectAll = !isSelectAll;
        if (isSelectAll) {
            $('.fields').each(function () {
                $(this).attr('checked', 'checked');
            });
        } else {
            $('.fields').each(function () {
                $(this).attr('checked', false);
            });
        }
    });
    $('#pop').hide();
    $('#notes').hide();
    $('#details').hide();
    //Show table configuration setting
    $('#setting').click(function () {
        $('#pop').bPopup();
    });
    //Close table configuration
    $('#cancelBtn').click(function () {
        $('#pop').bPopup().close();
    });

    //show advance options
    $('#advanceBtn').click(function () {
        advanceClick = !advanceClick;
        $('.advance').each(function () {
            if (advanceClick) $(this).show();
            else $(this).hide();
        });
    });
}

//Show popup when click account name
function ShowPopupByAccoutName(tableId, popId, notePopId) {
    var aData;
    $('#' + tableId + ' tr').each(function () {
        $(this).click(function () {
            var aPos = objTable.fnGetPosition(this);
            aData = objTable.fnGetData(aPos);//get data of the clicked row
        });
    });
    $('#' + tableId + ' tr td a').click(function () {
        $('#' + popId).bPopup(function () {
            setDataPopup(aData);
        });
    });
    $('#' + tableId + ' tr td span').click(function () {
        $('#' + notePopId).bPopup(function () {
            $('#' + notePopId).html(aData[16]);
        });
    });
}

//Fill data to popup details accont
function setDataPopup(aData) {
    $('#employeeId').html(aData[0]);
    $('#account').html(aData[1]);
    $('#fullName').html(aData[2]);
    $('#job').html(aData[3]);
    $('#department').html(aData[4]);
    $('#location').html(aData[8]);

}
//Close popup
function ClosePopup(senderId, popId) {
    $('#' + senderId).click(function () {
        $('#' + popId).bPopup().close();
    });
}

//Create Datatable 
function CreateDataTableById(id, columns, wrapper) {
    var cols = [];
    var arr = columns.split(',');
    for (var i = 0; i < arr.length; i++) {
        cols.push({
            "aTargets": [parseInt(arr[i])],
            "bVisible": false
        });
    }

    var obj = $("#" + id).dataTable(
        {
            "sDom": '<"wrapper"tpli>',
            "aLengthMenu": [[20, 50, 100, 150], [20, 50, 100, "All"]],
            "iDisplayLength": 20,
            "sPaginationType": "full_numbers",
            "aaSorting": [[1, "desc"]],
            "aoColumnDefs": cols,
            "bDestroy": true
        });
    $('.' + wrapper).addClass('configurationPaging');

    //search accout course using filters
    $('#searchAccountCourse').click(function () {
        getDataFromDatabase('dataTables', 1, $('#dataTables_length option:selected').text());
    });
    return obj;
}

//Hidden columns: hideColumns is list of columns which will hide : '1,4,6'
function ChangeTableConfiguration(senderId, tableId, columns, wrapper, popId, pageNumber, pageSize, totals) {
    $('#' + senderId).click(function () {
        var current = $('.paginate_active').text();
        hidden = getColumnsHide(columns);
        CreateDataTableById(tableId, hidden, wrapper);
        $('#' + popId).bPopup().close();
        configurationPaging(tableId, pageNumber, pageSize, totals);
        setCurrentPage(current, tableId);
        showTotalRecords(tableId, current, pageSize, totals);
    });
}

//get list of columns will hide ( not checked )
function getColumnsHide(className) {
    var hidden = '';
    $('.' + className).each(function (i) {
        if ($(this).prop('checked') == false) {
            hidden += i + ',';
        }
    });
    hidden += '17';
    return hidden;
}

//Paging configuration - IMPORTANT

function CreatePagingNumber(number, size, totals) {
    var page = Math.round(totals / size);
    if (eval(totals) % eval(size) > 0) page++;
    if (page > 0) {
        $('#dataTables_paginate span').html('');
        for (var i = 1; i <= page; i++) {
            $('#dataTables_paginate span').append('<a class="paginate_button" tabindex="0">' + (i) + '</a>');
            if (i == 5) {
                $('#dataTables_paginate span').append('<a class="paginate_button" tabindex="0">...</a>');
                break;
            }
        }
        $('#dataTables_paginate span a:eq(' + number + ')').removeClass('paginate_button');
        $('#dataTables_paginate span a:eq(' + number + ')').addClass('paginate_active');
    }
}

function getDataFromDatabase(idTable, pageNumber, pageSize) {
    var filters =
        $('#accName').val() + ',' +
            $('#employeeID').val() + ',' +
            '0,' +
            $('#courseName').val() + ',' +
            $('#fullName').val() + ',' +
            $('#courseStart').val() + ',' +
            $('#CourseEnd').val() + ',' +
            locationId + ',' +
            $('#accountStatus option:selected').text() +
            ',0,' +
            $('#courseYear').val() + ',' +
            $('#endDate').val() + ',' +
            $('#startDate').val() + ','
            + departmentId;
    $.ajax({
        "dataType": 'json',
        "type": "POST",
        "url": "/AccountCourse/AccountCoursePaging",
        "data": {
            pageNumber: pageNumber,
            pageSize: pageSize,
            filters: filters
        },
        "success": function (result) {
            var old = null;
            if (objTable.fnGetData(0) != null) {
                old = objTable.fnGetData(0)[17];
            }
            window.objTable.fnClearTable();
            for (var i = 0; i < result.length; i++) {
                window.objTable.fnAddData([
                    result[i].EmployeeId,
                    '<a href="javascript:;">' + result[i].AccountName + '</a>',
                    result[i].FullName,
                    result[i].JobTitleName,
                    result[i].Department,
                    result[i].CourseName,
                    result[i].Costs,
                    result[i].CurrencyName,
                    result[i].LocationName,
                    formatJSONDate(result[i].CourseStartDate),
                    formatJSONDate(result[i].EndDate),
                    result[i].PassCoverage,
                    result[i].TimeCommit,
                    result[i].CourseName,
                    result[i].TrainedDuration,
                    result[i].FinalResult,
                    result[i].Note,
                    result[i].TotalRows
                ]);
            }
            if (result.length == 0) {
                CreatePagingNumber(0, 1, 1);
            }
            if (objTable.fnGetData(0)[17] != old) {
                configurationPaging('dataTables', 0, $('#dataTables_length option:selected').text(), objTable.fnGetData(0)[17]);
            }

            ShowPopupByAccoutName('dataTables', 'details', 'notes');
            showTotalRecords(idTable, pageNumber - 1, pageSize, objTable.fnGetData(0)[17]);
        }
    });
}

//First Previous Next Last
function FPNL(idTable, pageSize, totals) {
    $('#' + idTable + '_first').click(function () {
        getDataFromDatabase(idTable, 1, pageSize, totals);
        CreatePagingNumber(0, pageSize, totals);
        showMorePage(idTable, pageSize, totals);
    });

    $('#' + idTable + '_last').click(function () {
        var m = Math.round(totals / pageSize);
        if (totals % pageSize > 0) m++;
        getDataFromDatabase(idTable, m, pageSize, totals);
        if (m - 3 > 0) {
            $('#dataTables_paginate span').html('<a class="paginate_button" tabindex="0">...</a>');
            $('#dataTables_paginate span').append('<a class="paginate_button" tabindex="0">' + (eval(m) - 2) + '</a>');
            $('#dataTables_paginate span').append('<a class="paginate_button" tabindex="0">' + (eval(m) - 1) + '</a>');
            $('#dataTables_paginate span').append('<a class="paginate_button" tabindex="0">' + m + '</a>');
        }
        setCurrentPage(m, idTable);
        $('#dataTables_paginate span a').click(function () {
            $('#dataTables_paginate span a').each(function () {
                $(this).removeClass('paginate_active');
                $(this).addClass('paginate_button');
            });
            getDataFromDatabase(idTable, $(this).text(), pageSize, totals);
            $(this).removeClass('paginate_button');
            $(this).addClass('paginate_active');
            showMorePage(idTable, pageSize, totals);
        });
    });

    $('#' + idTable + '_previous').click(function () {
        var current = $('.paginate_active').text();
        if (current > 1) {
            getDataFromDatabase(idTable, eval(current) - 1, pageSize, totals);
            setCurrentPage(eval(current) - 1, idTable);
        }
    });

    $('#' + idTable + '_next').click(function () {
        var current = $('.paginate_active').text();
        if (current < Math.round(totals / pageSize)) {
            getDataFromDatabase(idTable, eval(current) + 1, pageSize, totals);
            setCurrentPage(eval(current) + 1, idTable);
            alert(current);
        }
    });
}

//Set current page
function setCurrentPage(current, idTable) {
    $('#' + idTable + '_paginate span a').each(function () {
        if ($(this).text() != current) {
            $(this).removeClass('paginate_active');
            $(this).addClass('paginate_button');
        } else {
            $(this).removeClass('paginate_button');
            $(this).addClass('paginate_active');
        }
    });
}

//Show total-records
function showTotalRecords(idTable, current, pagesize, totals) {
    var s;
    if ((eval(current) + 1) * pagesize > totals) {
        s = totals;
    } else {
        s = (eval(current) + 1) * pagesize;
    }
    $('#' + idTable + '_info').html('Display from ' + eval(eval(current * pagesize) + 1) + ' to ' + s + ' of ' + totals + ' record(s)');
}

function configurationPaging(idTable, pageNumber, size, totals) {
    CreatePagingNumber(pageNumber, size, totals);
    $('#dataTables_paginate span a').click(function () {
        $('#dataTables_paginate span a').each(function () {
            $(this).removeClass('paginate_active');
            $(this).addClass('paginate_button');
        });
        getDataFromDatabase(idTable, $(this).text(), size, totals);
        $(this).removeClass('paginate_button');
        $(this).addClass('paginate_active');
        //todo
        showMorePage(idTable, size, totals);
    });
    FPNL(idTable, size, totals);
    showTotalRecords(idTable, pageNumber, size, totals);
}

function showMorePage(idTable, size, totals) {
    var current = $('.paginate_active').first().text();
    if (eval(current) > 3) {
        $('#dataTables_paginate span').html('<a class="paginate_button" tabindex="0">...</a>');
        $('#dataTables_paginate span').append('<a class="paginate_button" tabindex="0">' + (eval(current) - 2) + '</a>');
        $('#dataTables_paginate span').append('<a class="paginate_button" tabindex="0">' + (eval(current) - 1) + '</a>');
        $('#dataTables_paginate span').append('<a class="paginate_button" tabindex="0">' + (eval(current)) + '</a>');
        var max = Math.round(totals / size);
        if (totals % size > 0) max++;
        if (eval(current) < max - 3) {
            $('#dataTables_paginate span').append('<a class="paginate_button" tabindex="0">' + (eval(current) + 1) + '</a>');
        }
        if (eval(current) < max - 1) {
            $('#dataTables_paginate span').append('<a class="paginate_button" tabindex="0">' + (eval(current) + 2) + '</a>');
            $('#dataTables_paginate span').append('<a class="paginate_button" tabindex="0">' + (eval(current) + 3) + '</a>');
            $('#dataTables_paginate span').append('<a class="paginate_button" tabindex="0">...</a>');
        }
        setCurrentPage(current, idTable);
    } else {
        CreatePagingNumber(0, size, totals);
        setCurrentPage(current, idTable);
    }
    $('#dataTables_paginate span a').click(function () {
        $('#dataTables_paginate span a').each(function () {
            $(this).removeClass('paginate_active');
            $(this).addClass('paginate_button');
        });
        getDataFromDatabase(idTable, $(this).text(), size, totals);
        $(this).removeClass('paginate_button');
        $(this).addClass('paginate_active');
        //todo
        showMorePage(idTable, size, totals);
    });
}


